/**
 * 
 */
package com.orcwar.engine;

import java.util.List;

import com.orcwar.enums.DirectionEnum;

/**
 * @author Callil
 * 
 */
public class OWMap {

	private List<List<OWTile>> tiles;

	/** The left-upmost tile currently displayed. */
	private OWTile refTile;

	public OWMap() {

	}

	public List<List<OWTile>> getTiles() {
		return tiles;
	}

	public void setTiles(List<List<OWTile>> tiles) {
		this.tiles = tiles;
	}

	/**
	 * Returns the tile at this position. If the position is illegal, it will
	 * return <code>null</code>.
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	public OWTile getTile(int x, int y) {
		try {
			return tiles.get(y).get(x);
		} catch (IndexOutOfBoundsException e) {
			return null;
		}
	}

	public OWTile getTile(int id) {
		for (List<OWTile> row : tiles) {
			for (OWTile tile : row) {
				if (tile.getId() == id) {
					return tile;
				}
			}
		}
		return null;
	}

	public boolean areTileAdjacent(OWTile tile1, OWTile tile2) {
		return Math.abs(tile1.getX() - tile2.getX())
				+ Math.abs(tile1.getY() - tile2.getY()) == 1;
	}

	public void removeUnit(OWUnit target) {
		for (List<OWTile> row : tiles) {
			for (OWTile tile : row) {
				if (tile.getCurrentUnit() != null
						&& tile.getCurrentUnit().equals(target)) {
					tile.setCurrentUnit(null);
					break;
				}
			}
		}
	}

	public void addUnit(OWUnit unit, int x, int y) {
		getTile(x, y).setCurrentUnit(unit);
	}

	/**
	 * @return the refTile
	 */
	public OWTile getRefTile() {
		return refTile;
	}

	/**
	 * @param refTile
	 *            the refTile to set
	 */
	public void setRefTile(OWTile refTile) {
		this.refTile = refTile;
	}

	public void startNewTurnForAllUnits() {
		for (List<OWTile> row : tiles) {
			for (OWTile tile : row) {
				if (tile.getCurrentUnit() != null) {
					tile.getCurrentUnit().startNewTurn();
				}
			}
		}
	}
}
